package com.own.component.store.local.method.scheduler;

import com.own.component.store.local.method.base.BaseScheduler;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * StoreAtomicScheduler
 *
 * @author chenxueli
 * @date 2023-06-28 14:56:24
 */
public enum StoreAtomicScheduler implements BaseScheduler {

    /**
     * 当前实例
     */
    INSTANCE;

    private final AtomicInteger taskNumber = new AtomicInteger(1);
    private ScheduledExecutorService scheduler;

    StoreAtomicScheduler() {
        create();
    }


    /**
     * 创建
     */
    @Override
    public void create() {
        this.shutdown();
        this.scheduler = new ScheduledThreadPoolExecutor(10, r -> new Thread(r, String.format("store-atomic-%s", taskNumber.getAndIncrement())));
    }

    /**
     * 关闭
     */
    @Override
    public void shutdown() {
        if (null != scheduler) {
            this.scheduler.shutdown();
        }
    }

    /**
     * 定时
     *
     * @param task  任务
     * @param delay 延迟时间（毫秒）
     */
    @Override
    public void schedule(Runnable task, long delay) {
        this.scheduler.scheduleAtFixedRate(task, delay, delay, TimeUnit.MILLISECONDS);
    }

}

